﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using ETModel;
using System;

namespace ETHotfix
{

	[ObjectSystem]
	public class UIEffectAwakeSystem : AwakeSystem<UIEffect, int, UIEffectClass, Action>
	{
		public override void Awake(UIEffect self, int relativeOrder, UIEffectClass effectConfig, Action createCallback)
		{
			self.Awake(relativeOrder, effectConfig, createCallback).Coroutine();
		}
	}

	[HideInHierarchy]
	public class UIEffect : Component
    {
		private const string effectAbName = "effect";
		public string Name { get; private set; }

		private Renderer[] renderers;

		public async ETVoid Awake(int sortingOrder, UIEffectClass effectConfig,Action createCallback)
        {
			ResourcesComponent resourcesComponent = ETModel.Game.Scene.GetComponent<ResourcesComponent>();
			GameObject bundleGameObject = (GameObject)resourcesComponent.GetAsset(effectAbName.StringToAB(), effectConfig.effectPath);
			GameObject gameObject = UnityEngine.Object.Instantiate(bundleGameObject);
			this.GameObject = gameObject;
			this.Name = effectConfig.name + IdGenerater.GenerateId().ToString();
			this.renderers = this.GameObject.GetComponentsInChildren<Renderer>(true);
			SetSortingOrder(sortingOrder);
			if (createCallback != null)
			{
				createCallback();
			}
			if (effectConfig.liveTime > 0 && !effectConfig.isLoop)
			{
				await ETModel.Game.Scene.GetComponent<TimerComponent>().WaitAsync(effectConfig.liveTime);
				Dispose();
			}			
		}

        public override void Dispose()
        {
			if (this.IsDisposed)
			{
				return;
			}
			base.Dispose();
			Game.Scene.GetComponent<UIEffectComponent>().Remove(this);
			UnityEngine.Object.Destroy(GameObject);
		}

		public void SetSortingOrder(int order)
		{
			foreach (Renderer render in this.renderers)
			{
				render.sortingOrder = order;
			}
		}
    }

}
